import string

from irc.client import ServerConnectionError

from amgineirc.viewModel.viewModel import ViewModel

class ServersViewModel(ViewModel):
    good_chars = string.lowercase + '.' + string.digits
    def __init__(self, view, appdata):
        ViewModel.__init__(self, view)
        self._appdata = appdata
        itr = appdata['servers'].data.iteritems()
        for n, v in itr:
            self.view.vm_add_domain(n, v['port'], v['secure'], v['nick'], v['nick_password'])
        view.vm_option_command_handler = self.handle_option_command
        
    def handle_editor_command(self, command, key, domain, port, secure, nick, password):
        from amgineirc.view.settings.serversView import ServersView
        msg = []
        if command == ServersView.submit_command:
            if len(domain) == 0:
                msg.append('Server Domain Name is required.')
            else:
                bad_letters = False
                for i in domain:
                    if i not in ServersViewModel.good_chars:
                        msg.append("The Server Domain Name must only be lower case letters and dots.")
                        bad_letters = True
                        break
                if bad_letters is False:
                    if len(key) == 0 and domain in self._appdata['servers'].data:
                        msg.append("The Server Domain '%s' has already been added." % (domain))
            if len(port) == 0:
                msg.append('Server Port is required.')
            else:
                try:
                    iport = int(port)
                    if iport <= 0:
                        msg.append('Server Port must be a number greater than 0.')
                except:
                    msg.append('Server Port must be an integer.')
            if len(password) > 0 and len(nick) == 0:
                msg.append('You entered a Nick Password but not a Nick.')
            # check for settings folder
            if not self._appdata['servers'].have_configuration_folder():
                msg.append(self._appdata['servers'].missing_configuration_folder_message)
            ok = len(msg) == 0
            if ok:
                # form data is ok
                # the settings folder is present
                backup = self._appdata['servers'].backup()
                if len(key) > 0:
                    self._appdata['servers'].set_server(key,
                                                        domain,
                                                        iport,
                                                        secure,
                                                        nick,
                                                        password)
                    ok, smsg = self._appdata['servers'].save()
                    if ok is True:
                        self.view.vm_show_domain_edited(key,
                                                        domain,
                                                        iport,
                                                        secure,
                                                        nick,
                                                        password)
                    else:
                        self._appdata['servers'].restore(backup)
                    
                else:
                    self._appdata['servers'].add_server(domain,
                                                        iport,
                                                        secure,
                                                        nick,
                                                        password)
                    ok, smsg = self._appdata['servers'].save()
                    if ok is True:
                        self.view.vm_show_domain_added(domain,
                                                       iport,
                                                       secure,
                                                       nick,
                                                       password)
                    else:
                        self._appdata['servers'].restore(backup)
                msg.append(smsg)
        return (ok, "\n".join(msg))
        
    def handle_confirm_delete(self, truefalse, key):
        # the user has confirmed wanting to delete a server connection record
        if truefalse is True:
            ok = self._appdata['servers'].have_configuration_folder()
            if not ok:
                smsg = self._appdata['servers'].missing_configuration_folder_message
            else:
                backup = self._appdata['servers'].backup()
                del(self._appdata['servers'].data[key])
                ok, smsg = self._appdata['servers'].save()
                if not ok:
                    self._appdata['servers'].restore(backup)
            if ok:
                self.view.vm_show_domain_deleted(key)
            else:
                self.view.message_warn(smsg)

    def handle_option_command(self, command, key):
        from amgineirc.view.settings.serversView import ServersView, EditServerPopup
        if command == ServersView.edit_command:
            record = self._appdata['servers'].data[key]
            domain_used = self._appdata['trusted_users'].using_server(key) 
            popup = EditServerPopup(command,
                                    key,
                                    domain_used,
                                    record['port'],
                                    record['secure'],
                                    record['nick'],
                                    record['nick_password'],
                                    self.handle_editor_command)
            popup.open()
        elif command == ServersView.delete_command:
            domain_used = self._appdata['trusted_users'].using_server(key)
            if domain_used is True:
                # used by trusted users so can not delete
                self.view.message_warn('You can not delete %s because you have 1 or more trusted users there.' % (key))
            else:
                self.view.question_yes_no('Delete a Server Connection Record.',
                                          'Are you sure you want to permanently delete the server connection record for ' + key + '?',
                                          self.handle_confirm_delete,
                                          key)
        elif command == ServersView.create_command:
            record = self._appdata['servers'].default_record
            popup = EditServerPopup(command,
                                    record['domain'],
                                    False,
                                    record['port'],
                                    record['secure'],
                                    record['nick'],
                                    record['nick_password'],
                                    self.handle_editor_command)
            popup.open()
